package com.deimos.sps;

import org.vast.ows.OWSException;
import org.vast.ows.sps.CancelRequest;
import org.vast.ows.sps.CancelResponse;
import org.vast.ows.sps.StatusReport;
import org.vast.ows.sps.StatusReport.RequestStatus;
import org.vast.ows.sps.StatusReport.TaskStatus;
import org.vast.util.DateTime;
import com.deimos.Notification;
import com.deimos.dataBase.Event;
import com.deimos.dataBase.TaskController;

public class Cancel {
    CancelRequest request = null;
    CancelResponse response = null;

    public Cancel(CancelRequest request) {
	this.request = request;
    }

    public CancelResponse buildResponse() throws OWSException {
	String Id = request.getTaskID();
	StatusReport sr = new StatusReport();
	TaskController taskController = new TaskController();

	Event event = taskController.getLastEvent(Id);
	if (event != null) {
	    taskController.validateStatus(event.getTask().getTaskId());
	    if ((event.getRequestStatus() == RequestStatus.Accepted ||
		    event.getRequestStatus() == RequestStatus.Pending ||
		    event.getTaskStatus() == TaskStatus.InExecution ||
		    event.getTaskStatus() == TaskStatus.Reserved) && event.getTaskStatus() != TaskStatus.Cancelled
		    ) {
		event.setEventId(null);
		event.setTaskStatus(TaskStatus.Cancelled);
		event.setRequestStatus(null);
		event.setDescription("Task cancelled successfully");
		event.setUpdateDate(new DateTime());
		if (taskController.insertEvent(event)) {
		    sr.setDescription(event.getDescription());
		    sr.setRequestStatus(RequestStatus.Accepted);
		} else {
		    sr.setDescription("The task can not be cancelled");
		    sr.setRequestStatus(RequestStatus.Rejected);
		}
	    } else {
		sr.setDescription("The task can not be cancelled. Incorrect previous status.");
		sr.setRequestStatus(RequestStatus.Rejected);
	    }
	    sr.setTaskID(event.getTask().getTaskId());
	    if (event.getTask().getDelay() != null)
		sr.setEstimatedDelay(event.getTask().getDelay().intValue());
	    if (event.getEstimatedToC() != null)
		sr.setEstimatedToC(new DateTime(event.getEstimatedToC().getTime()));
	    if (event.getUpdateDate() != null)
		sr.setLastUpdate(new DateTime(event.getUpdateDate().getTime()));
	    sr.setTitle(event.getTask().getTitle());
	    sr.setSensorID(event.getTask().getSensorId());
	    Notification.notifyReport(event);
	} else {
	    throw new OWSException(OWSException.invalid_param_code, "task", request.getTaskID(), "The information was not found in the data base");
	}

	response = new CancelResponse();
	response.setVersion("2.0.0");
	response.setService("SPS");
	response.setReport(sr);

	return response;
    }

}
